package doantotnghiep.daoimpl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import doantotnghiep.dao.CategoryDao;
import doantotnghiep.model.Category;

public class CategoryDaoImpl implements CategoryDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Category> getListCategory() {
		return hibernateTemplate.find("from Category where status = 0  order by id");
	}

	@Override
	public void addCategory(Category category) {
		this.hibernateTemplate.saveOrUpdate(category);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public Category getCategoryByID(int id) {
		List<Category> categories = hibernateTemplate.find("from Category where status = 0  and id ="+ id);
		if(categories!=null){
			return categories.get(0);
		}
		return null;
	}

	@Override
	public void saveCategory(Category category) {
		this.hibernateTemplate.saveOrUpdate(category);	
	}

	@Override
	public void deleteCategory(int id) {
		Category entity = this.getCategoryByID(id);
		if (entity != null){
			entity.setStatus(1);
			this.hibernateTemplate.saveOrUpdate(entity);
		}
		
	}

	@Override
	public void inceaseNumberOfMedicine(int id) {
		Category entity = this.getCategoryByID(id);
		if (entity != null){
			entity.setNumberMedicine(entity.getNumberMedicine()+1);;
			this.hibernateTemplate.saveOrUpdate(entity);
		}
		
	}

}
